package com.kantboot.util.common.encryption;

import cn.hutool.core.util.IdUtil;
import org.springframework.stereotype.Component;

/**
 * kantboot加密算法
 */
@Component
public class KantbootSymmetricEncryption {

    /**
     * 生成密钥
     */
    public static String generateKey() {
        return IdUtil.simpleUUID();
    }

    /**
     * 加密
     */
    public static String encode(String content, String key) {
        // key的hashCode
        int keyHashCode = key.hashCode();
        // key的char数组
        char[] keyChars = key.toCharArray();
        // 加密
        char[] chars = content.toCharArray();
        // char对应的ASCII码值进行异或运算
        StringBuilder stringBuilder = new StringBuilder();
        // 异或加密
        for (int i = 0; i < chars.length; i++) {
            int i1 = chars[i] ^ keyHashCode + keyChars[i % keyChars.length];
            // 将i1转为32进制
            stringBuilder.append(Integer.toString(i1, 32)+"&");
        }
        // 去除最后一个&
        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

    /**
     * 解密
     */
    public static String decode(String content, String key) {
        // key的hashCode
        int keyHashCode = key.hashCode();
        // key的char数组
        char[] keyChars = key.toCharArray();
        // 解密
        String[] split = content.split("&");
        // char对应的ASCII码值进行异或运算
        StringBuilder stringBuilder = new StringBuilder();
        // 异或解密
        for (String s : split) {
            int i = Integer.parseInt(s, 32);
            stringBuilder.append((char) (i ^ keyHashCode + keyChars[(stringBuilder.length()) % keyChars.length]));
        }
        return stringBuilder.toString();
    }

}
